package com.yxjx.duoxue.network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.yxjx.duoxue.YxApplication;
import com.yxjx.duoxue.course.datamodel.AdDTS;
import com.yxjx.duoxue.course.datamodel.HomeAllAdData;
import com.yxjx.duoxue.database.YxDataBase;
import com.yxjx.duoxue.datamodel.DMActivity;
import com.yxjx.duoxue.datamodel.DMAdItem;
import com.yxjx.duoxue.datamodel.DMAllComments;
import com.yxjx.duoxue.datamodel.DMAppRef;
import com.yxjx.duoxue.datamodel.DMArea;
import com.yxjx.duoxue.datamodel.DMAuth;
import com.yxjx.duoxue.datamodel.DMCallRecord;
import com.yxjx.duoxue.datamodel.DMComment;
import com.yxjx.duoxue.datamodel.DMCommentLevel;
import com.yxjx.duoxue.datamodel.DMCommentLevelAvg;
import com.yxjx.duoxue.datamodel.DMCommentReply;
import com.yxjx.duoxue.datamodel.DMCourseCategory;
import com.yxjx.duoxue.datamodel.DMKeyword;
import com.yxjx.duoxue.datamodel.DMLocationPoints;
import com.yxjx.duoxue.datamodel.DMObject;
import com.yxjx.duoxue.datamodel.DMOpenApp;
import com.yxjx.duoxue.datamodel.DMProduct;
import com.yxjx.duoxue.datamodel.DMReportErrorItem;
import com.yxjx.duoxue.datamodel.DMSortBy;
import com.yxjx.duoxue.datamodel.DMTeacher;
import com.yxjx.duoxue.datamodel.DataList;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.datamodel.RushDTS;
import com.yxjx.duoxue.datamodel.config.ConfigRefundReasonDTS;
import com.yxjx.duoxue.datamodel.config.ConfigRefundTypeDTS;
import com.yxjx.duoxue.datamodel.course.CourseDetailDTS;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.datamodel.school.DMSchool;
import com.yxjx.duoxue.datamodel.school.SchoolDetailBrandDTS;
import com.yxjx.duoxue.datamodel.school.SchoolDetailEnvironmentDTS;
import com.yxjx.duoxue.datamodel.school.SchoolDetailServiceDTS;
import com.yxjx.duoxue.datamodel.school.SchoolDetailTeacherDTS;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;
import com.yxjx.duoxue.versionupdate.ConfigUpdateVersionDTS;

public class NwUtils {
	
	public static final String ROOT_URL = "http://api.learnmore.com.cn";
//	public static final String ROOT_URL = "http://192.168.1.241:8100";
//	public static final String ROOT_URL = "http://api.manytu.com";
	// H5字段URL
	public static final String ROOT_URL_PUBLIC = "http://www.learnmore.com.cn/m/";
	public static final String URL_COURSE_DESC = ROOT_URL_PUBLIC + "course_des.html?id=";
	public static final String URL_COURSE_ACHIEVE = ROOT_URL_PUBLIC + "course_achieve.html?id=";
	public static final String URL_SCHOOL_DESC = ROOT_URL_PUBLIC + "school_des.html?id=";
	public static final String URL_ACTIVITY_DESC = ROOT_URL_PUBLIC + "activity_des.html?id=";
	public static final String URL_TEACHER_DESC = ROOT_URL_PUBLIC + "teacher_des.html?id=";
	public static final String URL_TEACHER_ACHIEVE = ROOT_URL_PUBLIC + "teacher_achieve.html?id=";
	
	public static final String SURFIX_TAG = "";
	
	// school related
	public static final String REQ_SCHOOL_INFO = ROOT_URL + "/school/info.json";
	public static final String REQ_SCHOOL_LIST = ROOT_URL + "/school/list.json";
	// course related.
	public static final String REQ_COURSE_LIST = ROOT_URL + "/course/list.json";
	public static final String REQ_COURSE_INFO = ROOT_URL + "/course/info.json";
	// activity related.
	public static final String REQ_ACTIVITY_LIST = ROOT_URL + "/activity/list.json";
	public static final String REQ_ACTIVITY_INFO = ROOT_URL + "/activity/info.json";
	// teacher related.
	public static final String REQ_TEACHER_LIST = ROOT_URL + "/teacher/list.json";
	public static final String REQ_TEACHER_INFO = ROOT_URL + "/teacher/info.json";
	// course category.
	public static final String REQ_COURSE_CATEGORY = ROOT_URL + "/commons/courseType.json";
	// area category.
	public static final String REQ_AREA_CATEGORY = ROOT_URL + "/commons/area.json";
	// sort by
	public static final String REQ_SORT_BY = ROOT_URL + "/commons/order.json";
	
	// ad list.
	public static final String REQ_AD_LIST = ROOT_URL + "/commons/indexAd.json?areaId=1";
	// ref apps.
	public static final String REQ_REF_APPS = ROOT_URL + "/commons/appRecommend.json";
	
	// hot keywords.
	public static final String REQ_HOT_KEYWORDS = ROOT_URL + "/course/key.json";
	// user feedback.
	public static final String REQ_SUBMIT_APP_FEEDBACK = ROOT_URL + "/commons/suggestion.json";
	public static final String REQ_NPS = ROOT_URL + "/commons/nps.json";
	// 获取验证码
	public static final String REQ_MOBILE_CODE = ROOT_URL + "/reg/mobilecode.json";
	// 点评相关
	public static final String REQ_LIST_COMMENTS = ROOT_URL + "/comment/list.json";
    // 用户行为
	public static final String REQ_RECORD_CALL = ROOT_URL + "/commons/phoneCall.json";
	// APP启动记录
	public static final String REQ_OPEN_APP = ROOT_URL + "/commons/open.json";
	// HomePage 图标
	public static final String REQ_HOME_COURSE_CATEGORIES = ROOT_URL + "/commons/indexCourseType.json";
	// 报错项列表和提交报错
	public static final String REQ_LIST_REPORT_ERROR = ROOT_URL + "/config/problem.json";
	public static final String REQ_SUBMIT_REPORT_ERROR = ROOT_URL + "/commons/collectProblem.json";
	
	// 1课程/2活动/3学校/4老师
	public static final int RECORD_TYPE_COURSE = 1;
	public static final int RECORD_TYPE_ACTIVITY= 2;
	public static final int RECORD_TYPE_SCHOOL = 3;
	public static final int RECORD_TYPE_TEACHER = 3;
	// 分享相关的链接：
	public static final String SHARE_COURSE = "http://www.learnmore.com.cn/m/courseDetail.html?";
	public static final String SHARE_ACTIVITY = "http://www.learnmore.com.cn/m/activityDetail.html?";
	// 支付相关：
	public static final String BACK_URL = ROOT_URL + "/back/backUrl.json";
	public static final String REQ_ORDER_LIST = ROOT_URL + "/pay/orderList.json";
	public static final String REQ_ORDER_INFO = ROOT_URL + "/pay/orderInfo.json";
	public static final String REQ_PRODUCT_INFO = ROOT_URL + "/product/course.json";
	public static final String REQ_REFUND = ROOT_URL + "/commons/refund.json";
	public static final String REQ_PRODUCT_H5 = ROOT_URL_PUBLIC + "productDetail.html?id=";
	// 我的奖品
	public static final String URL_MY_COUPON = "http://www.learnmore.com.cn/m/userGift.html?sid=";
	// 用户付费协议
	public static final String URL_PAY_AGREEMENT = "http://www.learnmore.com.cn/index/userPayAgreement";
	// 检查是否有强制更新
	public static final String REQ_CHECK_FORCE_UPDATE = ROOT_URL + "/commons/update.json";
	
	public static final String KEY_PARAMS = "param";
	public static final String KEY_SID = "sid";
	public static final String KEY_AREA = "area";
	public static final String KEY_COUNT = "key_shown_count";
	public static final String KEY_ID = "id";
	public static final String KEY_NAME = "name";
	public static final String KEY_IMAGE = "image";
	public static final String KEY_START_INDEX = "startIndex";
	public static final String KEY_SCHOOL = "school";
	
	public static final String KEY_CATEGORY = "category";
	public static final String KEY_AGE = "age";
	public static final String KEY_ORDER_BY = "order";
	public static final String KEY_KEYWORD = "keyword";
	public static final String KEY_MOBILE_NUM = "mobile";
	
	
	public static Object requestDataInfo(String url, JSONObject params, Context context) throws JSONException, ClientProtocolException, IOException {
		return requestDataInfo(url, params, null, context);
	}
	
	public static Object requestDataInfo(String url, JSONObject params, UserLoginResponse ulRsp, Context context) throws JSONException, ClientProtocolException, IOException {
		
		if (params == null) {
			// for test
			params = new JSONObject();
			params.put(KEY_ID, "8");
		}
		
		HttpPost request = new HttpPost(url);
		
		List list = new ArrayList<BasicNameValuePair>();
		if (ulRsp != null) {
			// 带有登录信息时返回更详细的信息例如：收藏状态和收藏数等等。
			 list.add(new BasicNameValuePair(KEY_SID, ulRsp.getSid()));
		}
		list.add(new BasicNameValuePair(KEY_PARAMS, params.toString()));
		list.add(new BasicNameValuePair("device", Utils.getShortDeviceId(context)));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
		
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		String dataStr = jo.getString("data");
		JSONObject data = new JSONObject(dataStr);
		Log.d("CMM", "data = " + data);
		
		if (url.equals(REQ_COURSE_INFO)) {
			DMCourse course = new DMCourse();
			fillDataToCourse(data, course);
			return course;
		} else if (url.equals(REQ_TEACHER_INFO)) {
			DMTeacher teacher = new DMTeacher();
			fillDataToTeacher(data, teacher);
			return teacher;
		} else if (url.equals(REQ_SCHOOL_INFO)) {
			DMSchool school = new DMSchool();
			fillDataToSchool(data, school);
			return school;
		} else if (url.equals(REQ_ACTIVITY_INFO)) {
			DMActivity activity = new DMActivity();
			fillDataToActivity(data, activity);
			return activity;
		}
 		
		return null;
	}
	
	private static void fillDataToActivity(JSONObject data, DMActivity activity) {
		try {
			JSONObject activityJson = data.getJSONObject("activity");
			activity.setActivityName(activityJson.getString("actTitle"));
			activity.setActCount(activityJson.getInt("actCount"));
			activity.setActivityDes(activityJson.getString("actDes"));
			activity.setActivityId(activityJson.getLong("id"));
			activity.setActNowCount(activityJson.getInt("actNowCount"));
			activity.setContactPhone(activityJson.getString("contactPhone"));
			activity.setStartTime(activityJson.getLong("actBeginTime"));
			activity.setEndTime(activityJson.getLong("actEndTime"));
			activity.setHeadImageUrl(activityJson.getString("actImage"));
			activity.setHostName(activityJson.getString("schoolName"));
			activity.setSchoolGps(activityJson.getString("gps"));
			activity.setActivityName(activityJson.getString("actTitle"));
			activity.setAddrList(DMLocationPoints.from(activityJson.getJSONArray("addrList")));
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

	private static void fillDataToSchool(JSONObject data, DMSchool school) {
		try {
			JSONObject schoolJson = data.getJSONObject("school");
			school.setFullSchoolName(schoolJson.getString("schoolFullName"));
			school.setId(schoolJson.getLong("id"));
			school.setAddress(schoolJson.getString("address"));
			school.setPhoneNumbers(schoolJson.getString("contactPhone"));
			school.setSchoolImage(schoolJson.getString("schoolImage"));
			school.setSchoolGps(schoolJson.getString("gps"));
			school.setDescription(schoolJson.getString("discription"));
			school.setAchivement(schoolJson.getString("achieve"));
			fillJsonToDMAuthList(schoolJson.getJSONArray("auths"), school.getAuthArray());

			String mainCoursesStr = schoolJson.getString("mainCourse");
				if (!UIHelper.isEmpty(mainCoursesStr)) {
					JSONArray mainCourses = new JSONArray(mainCoursesStr);
					for (int j = 0; j < mainCourses.length(); j++) {
						JSONObject item = mainCourses.getJSONObject(j);
						DMCourseCategory category = new DMCourseCategory();
						category.setType((int) item.getLong("id"));
						category.setStr(item.getString("name"));
						school.getMainCourses().add(category);
					}
				}
			school.setSchoolCommentLevel(DMCommentLevelAvg.from(schoolJson.getString("schoolCommentLevel")));
			// 学校的四大类17个维度以及轮播图
			school.setSchoolBrand(SchoolDetailBrandDTS.from(schoolJson.getString("schoolBrand")));
			school.setSchoolEnviroment(SchoolDetailEnvironmentDTS.from(schoolJson.getString("schoolEnviroment")));
			school.setSchoolService(SchoolDetailServiceDTS.from(schoolJson.getString("schoolService")));
			school.setSchoolTeacher(SchoolDetailTeacherDTS.from(schoolJson.getString("schoolTeacher")));
			school.setImageTurn(schoolJson.getString("imageTurn"));
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private static void fillDataToTeacher(JSONObject data, DMTeacher teacher) {
		JSONObject teacherJson;
		try {
			teacherJson = data.getJSONObject("teacher");
			teacher.setIconUrl(teacherJson.getString("teacherImage"));
			teacher.setId(teacherJson.getLong("id"));
			teacher.setTeacherName(teacherJson.getString("teacherName"));
			teacher.setTeacherDesc(teacherJson.getString("teacherDes"));
			teacher.setTeacherAchievment(teacherJson.getString("teacherAchieve"));
			teacher.setFullSchoolName(teacherJson.getString("schoolName"));
			JSONArray coursesArray = teacherJson.getJSONArray("courses");
			for (int i = 0; i < coursesArray.length(); i++) {
				DMCourse course = new DMCourse();
				JSONObject courseJson = coursesArray.getJSONObject(i);
				course.setCourseId(courseJson.getLong("id"));
				course.setCourseName(courseJson.getString("name"));
				course.setCourseType1(courseJson.getString("firstTypeName"));
				course.setCourseType2(courseJson.getString("secondTypeName"));
				course.setHeadImageUrl(courseJson.getString("courseImage"));
				course.setPropAgeStart(courseJson.getInt("propAgeStart"));
				course.setPropAgeEnd(courseJson.getInt("propAgeEnd"));
				teacher.getCoursesArray().add(course);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	public static void fillDataToCourse(JSONObject data, DMCourse course) {
		try {
			// 课程的广告
			JSONObject adJson = DMObject.getJSONObject(data, "ad");
			if (adJson != null) {
				course.setAdItem(AdDTS.from(adJson));
			}
			
			// course
			JSONObject courseJson = data.getJSONObject("course");
			course.setCourseAchievement(DMObject.castString(courseJson, "courseAchieve"));
			course.setCourseDescription(DMObject.castString(courseJson, "courseDes"));
			course.setHeadImageUrl(DMObject.castString(courseJson, "courseImage"));
			course.setCourseId(DMObject.castLong(courseJson,"id"));
			course.setCourseName(DMObject.castString(courseJson, "courseName"));
			course.setCourseType1(DMObject.castString(courseJson, "firstTypeName"));
			course.setCourseType2(DMObject.castString(courseJson, "secondTypeName"));
			course.setPropAgeStart(getInt(courseJson, "propAgeStart", 0));
			course.setPropAgeEnd(getInt(courseJson, "propAgeEnd", 0));
			course.setSchoolFullName(DMObject.castString(courseJson,"schoolFullName"));
			course.setSchoolId(DMObject.castLong(courseJson,"schoolId"));
			course.setSupportBook(DMObject.castInteger(courseJson,"needBook"));
			course.setHeadImageUrl(DMObject.castString(courseJson,"courseImage"));
			course.setAddress(DMObject.castString(courseJson, "address"));
			course.setSchoolPhone(DMObject.castString(courseJson,"schoolPhone"));
			course.setFavStatus(DMObject.castInteger(courseJson,"favStatus"));
			// price
			course.setShowPackagePrice(DMObject.castInteger(courseJson, "showPerPrice"));
			course.setShowPerPrice(DMObject.castInteger(courseJson, "showPackagePrice"));
			course.setPerPrice(DMObject.castInteger(courseJson, "perPrice"));
			course.setPackagePrice(DMObject.castInteger(courseJson,"packagePrice"));
			// location
			course.setSchoolGps(DMObject.castString(courseJson,"gps"));
			course.setSchoolCommentLevel(DMCommentLevelAvg.from(courseJson.getString("schoolCommentLevel")));
			course.setCourseCommentLevel(DMCommentLevelAvg.from(courseJson.getString("courseCommentLevel")));
			JSONArray tearchersArray = courseJson.getJSONArray("teachers");
			for (int i = 0; i < tearchersArray.length(); i++) {
				DMTeacher teacher = new DMTeacher();
				JSONObject teacherJson = tearchersArray.getJSONObject(i);
				teacher.setId(teacherJson.getLong(KEY_ID));
				teacher.setTeacherName(teacherJson.getString(KEY_NAME));
				teacher.setIconUrl(teacherJson.getString(KEY_IMAGE));
				course.getTeachers().add(teacher);
			}
			fillJsonToDMAuthList(courseJson.getJSONArray("auths"), course.getAuthArray());
			// affinited school
			DMSchool school = new DMSchool();
			fillDataToSchool(courseJson, school);
			course.setSchool(school);
			// 商品列表
			fillDataToProductsList(courseJson, course);
			// 轮播图和课程详情（7维度)
			// TODO: "courseDetail"key对应的value是JSONObject对象，getString拿到的是其对象的toString结果。
			course.setCourseDetail(CourseDetailDTS.from(courseJson.getString("courseDetail")));
			course.setImageTurn(courseJson.getString("imageTurn"));
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private static void fillDataToProductsList(JSONObject courseJson,
			DMCourse course) {
		ArrayList<DMProduct> products = new ArrayList<DMProduct>();
		try {
			JSONArray ja = courseJson.getJSONArray("priceList");
			Utils.logd("CMM7 ja = " + ja + ", courseId = " + course.getCourseId());
			if (ja == null || ja.length() == 0) {
				return;
			}
			for (int i = 0; i < ja.length(); i++) {
				JSONObject jo = ja.getJSONObject(i);
				products.add(DMProduct.from(jo.toString()));
			}
			course.setProducts(products);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * request all course list.
	 * @param <E>
	 * @param urlStr
	 * @param context
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws JSONException
	 */
	public static <E> DataList<E> requestDataInfoList(String url, Context context) throws ClientProtocolException, IOException, JSONException {
		return requestDataInfoList(url, null, context);
	}
	
	/**
	 * request course/activity/teacher/comments list.
	 * @param url
	 * @param params
	 * @param context
	 * @return
	 * @throws JSONException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static <E> DataList<E> requestDataInfoList(String url, JSONObject params, Context context) throws JSONException, ClientProtocolException, IOException {
		return requestDataInfoList(url, params, null, context);
	}
	
	/**
	 * request course/activity/teacher/comments list.
	 * @param url
	 * @param params
	 * @param ulRsp
	 * @return
	 * @throws JSONException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static <E> DataList<E> requestDataInfoList(String url, JSONObject params, UserLoginResponse ulRsp, Context context) throws JSONException, ClientProtocolException, IOException {
		
		if (params == null) {
			params = new JSONObject();
			params.put(KEY_AREA, "0_0");
//			param.put(KEY_COUNT, 20);
		}
		
		HttpPost request = new HttpPost(url);
		
		List list = new ArrayList<BasicNameValuePair>();
		if (ulRsp != null) {
			// 带有登录信息时返回更详细的信息例如：收藏状态和收藏数等等。
			 list.add(new BasicNameValuePair(KEY_SID, ulRsp.getSid()));
		}
		list.add(new BasicNameValuePair(KEY_PARAMS, params.toString()));
		list.add(new BasicNameValuePair("device", Utils.getShortDeviceId(context)));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
		
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		String dataStr = jo.getString("data");
		JSONObject data = new JSONObject(dataStr);
		Log.d("CMM", "data = " + data);
		
		if (url.equals(REQ_COURSE_LIST)) {
			DataList<DMCourse> courses = new DataList<DMCourse>(0);
			fillDataToCourseArray(data, courses);
			return (DataList<E>) courses;
		} else if (url.equals(REQ_ACTIVITY_LIST)) {
			DataList<DMActivity> activities = new DataList<DMActivity>();
			fillDataToActivityArray(data, activities);
			return (DataList<E>) activities;
		} else if (url.equals(REQ_TEACHER_LIST)) {
			DataList<DMTeacher> teachers = new DataList<DMTeacher>();
			fillDataToTeacherArrary(data, teachers);
			return (DataList<E>) teachers;
		} else if (url.equals(REQ_SCHOOL_LIST)) {
			DataList<DMSchool> schools = new DataList<DMSchool>();
			fillDataToSchoolArray(data, schools);
			return (DataList<E>) schools;
		} else if (url.equals(REQ_LIST_COMMENTS)) {
			DataList<DMComment> comments = new DataList<DMComment>();
			fillDataToCommentArray(data, comments);
			return (DataList<E>) comments;
		}
		
		return null;
	}
	
	/**
	 * request comments list.
	 * @param url
	 * @param params
	 * @return
	 * @throws JSONException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static DMAllComments requestAllCommentsList(String url, JSONObject params, Context context) throws JSONException, ClientProtocolException, IOException {
		
		if (params == null) {
			params = new JSONObject();
			params.put(KEY_AREA, "0_0");
//			param.put(KEY_COUNT, 20);
		}
		
		HttpPost request = new HttpPost(url);
		
		List list = new ArrayList<BasicNameValuePair>();
		
		tryAddSidParamInternal(context, list);
		
		list.add(new BasicNameValuePair(KEY_PARAMS, params.toString()));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
		
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		String dataStr = jo.getString("data");
		JSONObject data = new JSONObject(dataStr);
		Log.d("CMM", "data = " + data);
		
		if (url.equals(REQ_LIST_COMMENTS)) {
			DMAllComments allComments = new DMAllComments();
			DataList<DMComment> comments = new DataList<DMComment>();
			fillDataToCommentArray(data, comments);
			allComments.setAllComments(comments);
			allComments.setTotalNum(data.getInt("tcount"));
			return allComments;
		}
		return null;
	}

	private static void tryAddSidParamInternal(Context context, List list) {
		UserLoginResponse ulRsp = UserLoginResponse.getInstance(context);
		if (ulRsp != null) {
			list.add(new BasicNameValuePair(KEY_SID, ulRsp.getSid()));
		}
	}	

	static void fillDataToCommentArray(JSONObject data,
			ArrayList<DMComment> comments) {
		try {
			JSONArray jsonArray = data.getJSONArray("comments");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonItem = jsonArray.getJSONObject(i);
				DMComment comment = DMComment.from(jsonItem.toString());
				DMCommentLevel commentLevel= DMCommentLevel.from(jsonItem.getString("level"));
				comment.setLevel(commentLevel);
				
				ArrayList<DMCommentReply> mCommentRepliies = new ArrayList<DMCommentReply>();
				String replies = jsonItem.getString("replys");
				JSONArray repliesJson = new JSONArray(replies);
				for (int j = 0; j < repliesJson.length(); j++) {
					DMCommentReply replyItem = DMCommentReply.from(repliesJson.get(j).toString());
					mCommentRepliies.add(replyItem);
				}
				comment.setReplys(mCommentRepliies);
				comments.add(comment);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

	private static void fillDataToSchoolArray(JSONObject data,
			DataList<DMSchool> schools) {
		try {
			JSONArray jsonArray = data.getJSONArray("schoolList");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonItem = jsonArray.getJSONObject(i);
				DMSchool schoolItem = new DMSchool();
				schoolItem.setSchoolImage(jsonItem.getString("schoolImage"));
				schoolItem.setId(jsonItem.getLong("id"));
				schoolItem.setFullSchoolName(jsonItem.getString("schoolFullName"));
				schoolItem.setSchoolGps(jsonItem.getString("gps"));
				schoolItem.setSchoolCommentLevel(DMCommentLevelAvg.from(jsonItem.getString("schoolCommentLevel")));

				fillJsonToDMAuthList(jsonItem.getJSONArray("auths"), schoolItem.getAuthArray());
				
				String mainCoursesStr = jsonItem.getString("mainCourse");
				if (!UIHelper.isEmpty(mainCoursesStr)) {
					JSONArray mainCourses = new JSONArray(mainCoursesStr);
					for (int j = 0; j < mainCourses.length(); j++) {
						JSONObject item = mainCourses.getJSONObject(j);
						DMCourseCategory category = new DMCourseCategory();
						category.setType((int) item.getLong("id"));
						category.setStr(item.getString("name"));
						schoolItem.getMainCourses().add(category);
					}
				}
				schools.add(schoolItem);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private static void fillDataToActivityArray(JSONObject data,
			DataList<DMActivity> activities) {
		try {
			JSONArray jsonArray = data.getJSONArray("list");
			for (int i = 0; i < jsonArray.length(); i++) {
				try {
					JSONObject jsonItem = jsonArray.getJSONObject(i);
					DMActivity activityItem = new DMActivity();
					activityItem.setActivityId(jsonItem.getLong("id"));
					activityItem.setActivityName(jsonItem.getString("actTitle"));
					activityItem.setHostName(jsonItem.getString("schoolName"));
					activityItem.setSchoolGps(jsonItem.getString("gps"));
					activityItem.setActivityDes(jsonItem.getString("actDes"));
					activityItem.setHeadImageUrl(jsonItem.getString("actImage"));
					activityItem.setStartTime(jsonItem.getLong("actBeginTime"));
					activityItem.setEndTime(jsonItem.getLong("actEndTime"));
					activityItem.setContactPhone(jsonItem.getString("contactPhone"));
					activityItem.setActCount(jsonItem.getInt("actCount"));
					activityItem.setActNowCount(jsonItem.getInt("actNowCount"));
					activityItem.setAddrList(DMLocationPoints.from(jsonItem.getJSONArray("addrList")));
					activityItem.setAddress(jsonItem.getString("actAddress"));
					activityItem.setVisitedCount(jsonItem.getInt("visitCount"));
					activityItem.setLeftDays(jsonItem.getString("leftDays"));
					activities.add(activityItem);
				}
				catch (JSONException e) {
					e.printStackTrace();
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}
	
	private static void fillDataToTeacherArrary(JSONObject data,
			ArrayList<DMTeacher> teachers) {
		try {
			JSONArray jsonArray = data.getJSONArray("teacherList");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonItem = jsonArray.getJSONObject(i);
				DMTeacher teacher = new DMTeacher();
				teacher.setId(jsonItem.getLong("id"));
				teacher.setTeacherName(jsonItem.getString("teacherName"));
				teacher.setIconUrl(jsonItem.getString("teacherImage"));
				teachers.add(teacher);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

	private static void fillDataToCourseArray(JSONObject data,
			DataList<DMCourse> courses) {
		try {
			
			// list 对应的广告
			JSONObject adJson = DMObject.getJSONObject(data, "ad");
			if (adJson != null) {
				courses.setAdItem(AdDTS.from(adJson));
			}
			
			// data List
			JSONArray jsonArray = data.getJSONArray("courseList");
			int length = jsonArray.length();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonItem = jsonArray.getJSONObject(i);
				DMCourse courseItem = new DMCourse();
				courseItem.setCourseId(jsonItem.getLong("id"));
				courseItem.setCourseName(jsonItem.getString("courseName"));
				courseItem.setCourseType1(jsonItem.getString("firstTypeName"));
				courseItem.setCourseType2(jsonItem.getString("secondTypeName"));
				courseItem.setPropAgeStart(getInt(jsonItem, "propAgeStart", 0));
				courseItem.setPropAgeEnd(getInt(jsonItem, "propAgeEnd", 0));
				courseItem.setSchoolFullName(jsonItem.getString("schoolFullName"));
				courseItem.setSchoolGps(jsonItem.getString("gps"));
				courseItem.setSchoolId(jsonItem.getLong("schoolId"));
				courseItem.setHeadImageUrl(jsonItem.getString("courseImage"));
				courseItem.setSupportBook(jsonItem.getInt("needBook"));
				courseItem.setSchoolCommentLevel(DMCommentLevelAvg.from(jsonItem.getString("schoolCommentLevel")));
				courseItem.setCourseCommentLevel(DMCommentLevelAvg.from(jsonItem.getString("courseCommentLevel")));
				
				JSONArray ja = jsonItem.getJSONArray("auths");
				fillJsonToDMAuthList(ja, courseItem.getAuthArray());
				courseItem.setDiscount(DMObject.getString(jsonItem, "discount"));
				courses.add(courseItem);
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}
	
	private static void fillJsonToDMAuthList(JSONArray ja, ArrayList<DMAuth> list) {
		if (list == null) {
			list = new ArrayList<DMAuth>();
		}
		if (ja != null && ja.length() > 0) {
			for (int i = 0; i < ja.length(); i++) {
				JSONObject jo;
				try {
					jo = ja.getJSONObject(i);
					DMAuth auth = DMAuth.from(jo.toString());
					list.add(auth);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	static int getInt(JSONObject jsonObject, String key, int def) {
		int ret = def;
		try {
			ret = jsonObject.getInt(key);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return ret;
	}
	
	/**
	 * get All Course info from server.
	 * 课程学校列表的课程类别分类，所有的一级和二级分类项存放在一个二维数组中。
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws JSONException 
	 * @throws ParseException 
	 */
	public static ArrayList<ArrayList<DMCourseCategory>> requestCourseCategories(Context context) throws ClientProtocolException, IOException, ParseException, JSONException {
		ArrayList<ArrayList<DMCourseCategory>> ret = new ArrayList<ArrayList<DMCourseCategory>>();
		
		HttpPost request = new HttpPost(REQ_COURSE_CATEGORY);
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		String dataStr = jo.getString("data");
		JSONObject dataJson = new JSONObject(dataStr);
		// 添加全城或者全部课程的选项
		ArrayList<DMCourseCategory> firstRow = new ArrayList<DMCourseCategory>();
		firstRow.add(new DMCourseCategory(-1, "所有课程"));
		ret.add(firstRow);
		// end
		
		JSONArray level1sJson = dataJson.getJSONArray("courseTypes");
		for (int i = 0; i < level1sJson.length(); i++) {
			JSONObject level1Json = level1sJson.getJSONObject(i);
			
			ArrayList<DMCourseCategory> level1Object = new ArrayList<DMCourseCategory>();
			ret.add(level1Object);
			
			DMCourseCategory item = new DMCourseCategory();
			// extract the parent item:
			item.setStr(DMObject.castString(level1Json,"typeName"));
			item.setType(DMObject.castInteger(level1Json, "id"));
			item.setIconUrl(DMObject.castString(level1Json,"typeIcon"));
			level1Object.add(item);
			// add all children items:
			JSONArray level2sJson = level1Json.getJSONArray("courseTypes");
			for (int j = 0; j < level2sJson.length(); j++) {
				if (j == 0) {
					level1Object.add(new DMCourseCategory(-1, "全部"));
				}
				JSONObject level2Json = level2sJson.getJSONObject(j);
				DMCourseCategory level2Item = new DMCourseCategory();
				level2Item.setStr(DMObject.castString(level2Json, "typeName"));
				level2Item.setType(DMObject.castInteger(level2Json, "id"));
				level2Item.setIconUrl(DMObject.castString(level2Json, "typeIcon"));
				level1Object.add(level2Item);
				item.getSubCategories().add(level2Item);
			}
		}
		
		return ret;
	}
	
	/**
	 * Request all area info by city id.
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws ParseException
	 * @throws JSONException
	 */
	public static ArrayList<ArrayList<DMArea>> requestAllAreas(int cityId, Context context) throws ClientProtocolException, IOException, ParseException, JSONException {
		// default city is Beijing 828.
		cityId = 828;
		ArrayList<ArrayList<DMArea>> ret = new ArrayList<ArrayList<DMArea>>();
		
		HttpPost request = new HttpPost(REQ_AREA_CATEGORY);
		
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("areaId", "" + cityId));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
		
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		String dataStr = jo.getString("data");
		JSONObject dataJson = new JSONObject(dataStr);
		
		// 获取Area区域
		ArrayList<DMArea> firstRow = new ArrayList<DMArea>();
		DMArea temp = new DMArea();
		temp.setAreaName("全城");
		temp.setAreaEname("AllArea");
		temp.setId(-1);
		temp.setLevel(1);
		firstRow.add(temp);
		ret.add(firstRow);
		//
		
		JSONArray level1sJsonArray = dataJson.getJSONArray("areas");
		JSONObject level1JsonObj = level1sJsonArray.getJSONObject(0);
		level1sJsonArray = level1JsonObj.getJSONArray("areas");
		
		for (int i = 0; i < level1sJsonArray.length(); i++) {
			ArrayList<DMArea> level1Object = new ArrayList<DMArea>();
			ret.add(level1Object);
			
			JSONObject level2sJsonObject = level1sJsonArray.getJSONObject(i);
			DMArea area = new DMArea();
			area.setAreaEname(level2sJsonObject.getString("areaEname"));
			area.setAreaName(level2sJsonObject.getString("areaName"));
			area.setId(level2sJsonObject.getInt("id"));
			area.setLevel(level2sJsonObject.getInt("level"));
			level1Object.add(area);
			
			// 加入“全部”二级菜单 TODO:加入二级区域信息。
			DMArea subArea = new DMArea();
			// 附近没有全部这一项。
			if (!area.getAreaName().equals("附近")) {
				subArea.setAreaEname("quanbu");
				subArea.setAreaName("全部");
				subArea.setId(-1);
				subArea.setLevel(0);
				level1Object.add(subArea);
			}
			
			JSONArray children = level2sJsonObject.getJSONArray("areas");
			for (int j = 0; j < children.length(); j++) {
				JSONObject subAreaJson = children.getJSONObject(j);
				subArea = new DMArea();
				subArea.setAreaEname(subAreaJson.getString("areaEname"));
				subArea.setAreaName(subAreaJson.getString("areaName"));
				subArea.setId(subAreaJson.getInt("id"));
				subArea.setLevel(subAreaJson.getInt("level"));
				level1Object.add(subArea);
			}
		}
		return ret;
	}
	
	public static ArrayList<DMCourseCategory> requestHomeCourseCategories(Context context) throws ClientProtocolException, IOException, ParseException, JSONException {
		HttpPost request = new HttpPost(REQ_HOME_COURSE_CATEGORIES);

		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity,
				"UTF-8"));

		int code = jo.getInt("code");
		if (code == MsgCode.SUCCESS) {
			JSONArray ja = jo.getJSONArray("indexCourseTypeList");
			ArrayList<DMCourseCategory> ret = new ArrayList<DMCourseCategory>();
			for (int i = 0; i < ja.length(); i++) {
				ret.add(DMCourseCategory.fromIndexCourseType(ja.get(i).toString()));
			}
			return ret;
		}
		return null;
	}
	/**
	 * 首页广告列表
	 * @param context
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws ParseException
	 * @throws JSONException
	 */
	public static HomeAllAdData requestAdList(Context context) throws ClientProtocolException, IOException, ParseException, JSONException {
		HomeAllAdData ret = new HomeAllAdData();
		ArrayList<DMAdItem> bannerAds = new ArrayList<DMAdItem>();
		
		HttpPost request = new HttpPost(REQ_AD_LIST);
		
		// sid可选
		List list = new ArrayList<BasicNameValuePair>();
		UserLoginResponse ulRsp = UserLoginResponse.getInstance(context);
		if (ulRsp != null) {
			list.add(new BasicNameValuePair("sid", ulRsp.getSid()));
		}
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
				
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		String dataStr = jo.getString("data");
		JSONObject dataJson = new JSONObject(dataStr);
		
		JSONArray level1sJson = dataJson.getJSONArray("ad");
		for (int i = 0; i < level1sJson.length(); i++) {
			JSONObject item = level1sJson.getJSONObject(i);
			DMAdItem ad = new DMAdItem("", 0, 0);
			ad.setAdId(item.getInt("id"));
			ad.setAdType(item.getInt("type"));
			ad.setItemId(item.getInt("typeId"));
			ad.setImageUrl(item.getString("imageUrl"));
			ad.setTitle(item.getString("title"));
			ad.setNeedLogin(item.getInt("login"));
			ad.setPageUrl(item.getString("pageUrl"));
			ad.setDes(DMObject.castString(item, "des"));
			bannerAds.add(ad);
		}
		ret.setBannerAds(bannerAds);
		ret.setRush(RushDTS.from(DMObject.getString(dataJson, "rush")));
		ret.setArea4(AdDTS.arrayFrom(DMObject.getString(dataJson, "area4")));
		ret.setArea5(AdDTS.arrayFrom(DMObject.getString(dataJson, "area5")));
		return ret;
	}
	
	/**
	 * 获取课程/学校列表时到排序方式列表。
	 * @param context
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws ParseException
	 * @throws JSONException
	 */
	public static ResponseObject requestSortBys(Context context) throws ClientProtocolException, IOException, ParseException, JSONException {
		HttpPost request = new HttpPost(REQ_SORT_BY);
		
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		ResponseObject retRsp = new ResponseObject(jo.getInt("code"), DMObject.getString(jo, UserReg.KEY_MESSAGE));
		
		Globals.getInstance(context).setSortBysCourse(new ArrayList<DMSortBy>());
		String dataStr1 = jo.getString("courseOrders");
		JSONArray dataJson = new JSONArray(dataStr1);
		for (int i = 0; i < dataJson.length(); i++) {
			JSONObject item = dataJson.getJSONObject(i);
			DMSortBy sortBy = DMSortBy.from(item.toString());
			if (sortBy != null) {
				Globals.getInstance(context).getSortBysCourse().add(sortBy);
			}
		}
		
		Globals.getInstance(context).setSortBysSchool(new ArrayList<DMSortBy>());
		String dataStr2 = jo.getString("schoolOrders");
		JSONArray dataJson2 = new JSONArray(dataStr2);
		for (int i = 0; i < dataJson2.length(); i++) {
			JSONObject item = dataJson2.getJSONObject(i);
			DMSortBy sortBy = DMSortBy.from(item.toString());
			if (sortBy != null) {
				Globals.getInstance(context).getSortBysSchool().add(sortBy);
			}
		}			
		return retRsp;
	}
	
	/**
	 * Get ref apps list by current channelCode.
	 * such as, http://api.manytu.com/commons/appRecommend.json?sign=yyb
	 * @param context
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws JSONException 
	 * @throws ParseException 
	 */
	public static ArrayList<DMAppRef> requestAllRefApps(Context context) throws ClientProtocolException, IOException, ParseException, JSONException {
		
		ArrayList<DMAppRef> ret = new ArrayList<DMAppRef>();
		HttpPost request = new HttpPost(REQ_REF_APPS);
		
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("sign", "" + Utils.getChannelCode(context)));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
				
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		String dataStr = jo.getString("data");
		JSONObject dataJson = new JSONObject(dataStr);
		
		JSONArray level1sJson = dataJson.getJSONArray("recommends");
		for (int i = 0; i < level1sJson.length(); i++) {
			JSONObject item = level1sJson.getJSONObject(i);
			DMAppRef app = new DMAppRef();
			app.setTitle(item.getString("title"));
			app.setIconUrl(item.getString("imageUrl"));
			app.setPackageName(item.getString("packageName"));
			app.setDesc(item.getString("des"));
			ret.add(app);
		}
			
		return ret;
	}
	
	/**
	 * Favourite a course.
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws JSONException
	 */
	public static ArrayList<DMKeyword> requestSearchKeywords(Context context) throws ClientProtocolException, IOException, JSONException {
		ArrayList<DMKeyword> ret = new ArrayList<DMKeyword>();
		
		HttpPost request = new HttpPost(REQ_HOT_KEYWORDS);
		
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		// query condition.
		JSONObject params = new JSONObject();
		try {
			params.put("area", "0_0");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		list.add(new BasicNameValuePair("param", "" + params.toString()));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
				
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		String dataStr = jo.getString("data");
		JSONObject dataJson = new JSONObject(dataStr);
		
		JSONArray level1sJson = dataJson.getJSONArray("keys");
		for (int i = 0; i < level1sJson.length(); i++) {
			JSONObject item = level1sJson.getJSONObject(i);
			DMKeyword key = new DMKeyword();
			key.setId(item.getInt("id"));
			key.setWord(item.getString("name"));
			ret.add(key);
		}
			
		return ret;
	}
	
	/**
	 * Submit user feedback to server.
	 * @param context
	 * @param text
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws ParseException
	 * @throws JSONException
	 */
	public static ResponseObject submitFeedback(Context context, String text) throws ClientProtocolException, IOException, ParseException, JSONException {
		
		HttpPost request = new HttpPost(REQ_SUBMIT_APP_FEEDBACK);
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("content", text));
		list.add(new BasicNameValuePair("version", Utils.getAppVersionName(context)));
		list.add(new BasicNameValuePair("device", Utils.getSoftwareInfo()
				+ " "+ Utils.getHardwareInfo(context)));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));

		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity,
				"UTF-8"));

		return new ResponseObject(jo.getInt("code"), DMObject.getString(jo, UserReg.KEY_MESSAGE));
	}
	
	public static ResponseObject submitNps(Context context, String grade) throws ClientProtocolException, IOException, ParseException, JSONException {
		
		HttpPost request = new HttpPost(REQ_NPS);
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("level", grade));
		list.add(new BasicNameValuePair("version", Utils.getAppVersionName(context)));
		list.add(new BasicNameValuePair("device", Utils.getSoftwareInfo()
				+ " "+ Utils.getHardwareInfo(context)));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));

		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity,
				"UTF-8"));

		return new ResponseObject(jo.getInt("code"), DMObject.getString(jo, UserReg.KEY_MESSAGE));
	}
	
	/**
	 * 获取手机验证码
	 * @param context
	 * @param number
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws JSONException 
	 * @throws ParseException 
	 */
	public static ResponseObject requestMobileCode(Context context, String number) throws ClientProtocolException, IOException, ParseException, JSONException {
		HttpPost request = new HttpPost(REQ_MOBILE_CODE);
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair(KEY_MOBILE_NUM, number));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));

		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity,
				"UTF-8"));

		return new ResponseObject(jo.getInt("code"), DMObject.getString(jo, UserReg.KEY_MESSAGE));
	}
	
	public static ResponseObject submitCallBehavior(Context context, DMCallRecord record) throws ClientProtocolException, IOException, ParseException, JSONException {
		if (record == null) {
			return new ResponseObject(-1, "");
		}
		HttpPost request = new HttpPost(REQ_RECORD_CALL);
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("device", record.getDevice()));
		list.add(new BasicNameValuePair("sid", record.getSid()));
		list.add(new BasicNameValuePair("version", record.getVersion()));
		list.add(new BasicNameValuePair("id", "" + record.getId()));
		list.add(new BasicNameValuePair("type", "" + record.getType()));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));

		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity,
				"UTF-8"));

		return new ResponseObject(jo.getInt("code"), DMObject.getString(jo, UserReg.KEY_MESSAGE));
	}
	
	public static ResponseObject submitOpenAppBehavior(Context context, DMOpenApp item) throws ClientProtocolException, IOException, ParseException, JSONException {
		if (item == null) {
			return new ResponseObject(-1, "");
		}
		HttpPost request = new HttpPost(REQ_OPEN_APP);
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("device", item.getDevice()));
		list.add(new BasicNameValuePair("version", item.getVersion()));
		list.add(new BasicNameValuePair("mark", ""));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));

		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity,
				"UTF-8"));

		return new ResponseObject(jo.getInt("code"), DMObject.getString(jo, UserReg.KEY_MESSAGE));
	}
	
	/**
	 * 请求refund的还款方式列表和还款原因列表,并写到AppDataModel。
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws JSONException 
	 * @throws ParseException 
	 */
	public static ResponseObject requestRefundInfo(Context context) throws ClientProtocolException, IOException, ParseException, JSONException {
		Globals model = Globals.getInstance(context);
		
		HttpPost request = new HttpPost(REQ_REFUND);
		
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("device", Utils.getShortDeviceId(context)));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
		
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		String dataStr1 = jo.getString("refundReasonList");
		model.setRefundReasons(new ArrayList<ConfigRefundReasonDTS>());
		JSONArray ja = new JSONArray(dataStr1);
		for (int index = 0; index < ja.length(); index++) {
			ConfigRefundReasonDTS reason = ConfigRefundReasonDTS.from(ja.getJSONObject(index).toString());
			if (reason != null) {
				model.getRefundReasons().add(reason);
			}
		}
		String dataStr2 = jo.getString("refundTypeList");
		model.setRefundTypes(new ArrayList<ConfigRefundTypeDTS>());
		ja = new JSONArray(dataStr2);
		for (int index = 0; index < ja.length(); index++) {
			ConfigRefundTypeDTS type = ConfigRefundTypeDTS.from(ja.getJSONObject(index).toString());
			if (type != null) {
				model.getRefundTypes().add(type);
			}
		}
		return new ResponseObject(jo.getInt("code"), DMObject.getString(jo, UserReg.KEY_MESSAGE));
	}
	
	/**
	 * 请求全部课程分类页面。TODO
	 * 首页点击全部项后展示详细的课程类别项信息（因为DMCourseCategory是递归嵌套的对象，用一维度的列表来表示），
	 * 此API与requestCourseCategories有一些不一致。
	 * @param context
	 * @return
	 */
	public static ArrayList<DMCourseCategory> requestDetailedCourseTypes(Context context) {
		return null;
	}
	
	/**
	 * 请求报错列表项
	 * @param context
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws ParseException
	 * @throws JSONException
	 */
	public static ArrayList<DMReportErrorItem> requestReportErrorItemList(Context context) throws ClientProtocolException, IOException, ParseException, JSONException {
		
		HttpPost request = new HttpPost(REQ_LIST_REPORT_ERROR);
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		if (code == MsgCode.SUCCESS) {
			ArrayList<DMReportErrorItem> list = new ArrayList<DMReportErrorItem>();
			JSONArray ja = jo.getJSONArray("dtsList");
			for (int i = 0; i < ja.length(); i++) {
				DMReportErrorItem item = DMReportErrorItem.from(ja.get(i).toString());
				if (item != null) {
					list.add(item);
				}
			}
			return list;
		} else {
			return null;
		}
	}

	/**
	 * 报错提交到服务器
	 * sid 登录用户的属性 id 对应的问题id，上面接口中的id type 对应类型1课程,2活动,3学校,4老师
	 * typeId 对应课程、活动、学校、老师的id
	 * @param context
	 * @param errorId
	 * @param type
	 * @param typeId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws ParseException
	 * @throws JSONException
	 */
	public static ResponseObject submitReprotError(Context context, int errorId, int type, String typeId) throws ClientProtocolException, IOException, ParseException, JSONException {
		
		HttpPost request = new HttpPost(REQ_SUBMIT_REPORT_ERROR);
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		
		// sid可选
		UserLoginResponse ulRsp = UserLoginResponse.getInstance(context);
		if (ulRsp != null) {
			list.add(new BasicNameValuePair("sid", ulRsp.getSid()));
		}
		
		list.add(new BasicNameValuePair("id", "" + errorId));
		list.add(new BasicNameValuePair("typeId", "" + typeId));
		list.add(new BasicNameValuePair("type", "" + type));
		list.add(new BasicNameValuePair("version", Utils.getAppVersionName(context)));
		list.add(new BasicNameValuePair("device", Utils.getSoftwareInfo()
				+ " "+ Utils.getHardwareInfo(context)));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));

		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity,
				"UTF-8"));

		return new ResponseObject(jo.getInt("code"), DMObject.getString(jo, UserReg.KEY_MESSAGE));
	}
	
	/**
	 * web 请求后面添加一个时间戳，避免缓存的影响。
	 * @return
	 */
	public static String webTail() {
		return "&time=" + System.currentTimeMillis();
	}
	
	public static ConfigUpdateVersionDTS queryForceUpdateFromWeb(Context context) throws JSONException, ClientProtocolException, IOException {
		HttpPost request = new HttpPost(REQ_CHECK_FORCE_UPDATE);
		
		// set query condition.
		List list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("version", "" + Utils.getFullDeviceId(context)));
		list.add(new BasicNameValuePair("device", "" + Utils.getFullDeviceId(context)));
		request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
				
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity responseEntity = response.getEntity();
		JSONObject jo = new JSONObject(EntityUtils.toString(responseEntity, "UTF-8"));
		
		int code = jo.getInt("code");
		if (code == MsgCode.SUCCESS) {
			return ConfigUpdateVersionDTS.from(jo.getString("dts"));
		}
		return null; 
	}
}
